package com.ahnu.tongue.utils;

import com.ahnu.tongue.common.BusinessException;
import com.ahnu.tongue.config.WeChatConfig;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.text.MessageFormat;

@Slf4j
@Component
@RequiredArgsConstructor
public class WeChatUtils {

    private final WeChatConfig weChatConfig;
    private final RestTemplate restTemplate;

    public String code2Session(String code) {
        String url = MessageFormat.format(WeChatConfig.CODE2SESSION_URL,
                weChatConfig.getAppId(),
                weChatConfig.getAppSecret(),
                code);

        try {
            String response = restTemplate.getForObject(url, String.class);
            JSONObject jsonObject = JSON.parseObject(response);

            if (jsonObject.getInteger("errcode") != null && jsonObject.getInteger("errcode") != 0) {
                log.error("微信登录失败：{}", response);
                throw new BusinessException("微信登录失败");
            }

            return jsonObject.getString("openid");
        } catch (Exception e) {
            log.error("调用微信接口失败", e);
            throw new BusinessException("微信登录失败");
        }
    }
} 